package com.yunxi.core.model;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class ValidateUtil<T> {
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    private static Validator validator = validatorFactory.getValidator();

    /**
     * 验证请求参数
     *
     * @param model
     * @return null 则说明验证成功，如果非null 则说明验证失败
     */
    public String validate(T model) {
        model.getClass().getAnnotatedInterfaces();
        Set<ConstraintViolation<T>> violations = validator.validate(model);
        if (violations.size() > 0) {
            String msg = "";
            for (ConstraintViolation<T> violation : violations) {
                msg += violation.getMessage() + "<br>";
            }
            return msg;
        }
        return null;
    }
}